package com.kfm.loginIp.util;

import com.kfm.loginIp.enums.SmsTemplateEnum;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author Aurora雪
 */
@Component
public class TencentSmsUtil {
    private final StringRedisTemplate redisTemplate;

    @Autowired
    public TencentSmsUtil(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    //测试发短信功能
    public boolean sendSms(String phoneNumber, String verificationCode) {
        String key = Constant.RETRIEVE_VERIFICATION_CODE + phoneNumber;
        System.out.println(verificationCode);
        // 存入Redis验证码5分钟内有效,过期后删除
        redisTemplate.opsForValue().set(key, verificationCode, 5, TimeUnit.MINUTES);
        return true;
    }

    /**
     * 发送注册短信验证码
     *
     * @param phoneNumber 手机号码
     * @param verificationCode 验证码
     * @return 是否发送成功
     */
    public boolean registerVerificationCode(String phoneNumber, String verificationCode) {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户密钥对secretId，secretKey
            Credential cred = new Credential(TencentCredentialsReaderUtil.getSecretId(), TencentCredentialsReaderUtil.getSecretKey());

            HttpProfile httpProfile = new HttpProfile();// 实例化一个http选项，可选，没有特殊需求可以跳过
            httpProfile.setEndpoint("sms.tencentcloudapi.com");// 指定接入地域

            ClientProfile clientProfile = new ClientProfile();// 实例化一个client选项，可选，没有特殊需求可以跳过
            clientProfile.setHttpProfile(httpProfile);

            SmsClient client = new SmsClient(cred, "", clientProfile);

            SendSmsRequest req = new SendSmsRequest();
            // 短信应用ID
            req.setSmsSdkAppid(Constant.SDK_APP_ID);
            // 短信签名
            req.setSign(Constant.SIGN_NAME);
            // 短信模板ID
            req.setTemplateID(SmsTemplateEnum.REGISTER.getTemplateID());
            req.setPhoneNumberSet(new String[] { phoneNumber });// 手机号码
            // 添加模板参数，包括验证码和过期时间
            req.setTemplateParamSet(new String[] { verificationCode, "5" });// 验证码和过期时间

            SendSmsResponse resp = client.SendSms(req);

//            System.out.println(resp.getSendStatusSet()[0].getCode());

            if (resp.getSendStatusSet()[0].getCode().equals("Ok")) {
                // 将验证码存储到Redis，并设置过期时间为5分钟
                String key = Constant.REGISTER_VERIFICATION_CODE + phoneNumber;//防止冲突
                redisTemplate.opsForValue().set(key, verificationCode, 5, TimeUnit.MINUTES);
//                System.out.println(verificationCode);
                return true;
            } else {
                return false;
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 验证用户输入的注册验证码
     *
     * @param phoneNumber 手机号码
     * @param userInputCode 用户输入的验证码
     * @return 验证结果
     */
    public boolean inputVerifyVerificationCode(String phoneNumber, String userInputCode) {
        String key = Constant.REGISTER_VERIFICATION_CODE + phoneNumber;//防止冲突
        String storedCode = redisTemplate.opsForValue().get(key);
        System.out.println(storedCode);
        if (userInputCode.equals(storedCode)) {
            // 验证通过
            return true;
        } else {
            // 验证失败
            return false;
        }
    }

    /**
     * 生成6位的随机验证码
     */
    public static String generateVerificationCode() {
        // 生成6位的随机验证码
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        return String.valueOf(code);
    }

    /**
     * 发送忘记密码短信验证码
     *
     * @param phoneNumber 手机号码
     * @param verificationCode 验证码
     * @return 是否发送成功
     */
    public boolean retrieveVerificationCode(String phoneNumber, String verificationCode) {
        try {
            Credential cred = new Credential(TencentCredentialsReaderUtil.getSecretId(), TencentCredentialsReaderUtil.getSecretKey());

            HttpProfile httpProfile = new HttpProfile();// 实例化一个http选项，可选，没有特殊需求可以跳过
            httpProfile.setEndpoint("sms.tencentcloudapi.com");// 指定接入地域

            ClientProfile clientProfile = new ClientProfile();// 实例化一个client选项，可选，没有特殊需求可以跳过
            clientProfile.setHttpProfile(httpProfile);

            // 实例化要请求产品(以sms为例)的client对象
            SmsClient client = new SmsClient(cred, "", clientProfile);

            SendSmsRequest req = new SendSmsRequest();
            // 短信应用ID
            req.setSmsSdkAppid(Constant.SDK_APP_ID);
            // 短信签名
            req.setSign(Constant.SIGN_NAME);
            // 短信模板ID
            req.setTemplateID(SmsTemplateEnum.FORGET_PASSWORD.getTemplateID());
            req.setPhoneNumberSet(new String[] { phoneNumber });// 手机号码
            // 添加模板参数，包括验证码和过期时间
            req.setTemplateParamSet(new String[] { verificationCode });// 验证码

            SendSmsResponse resp = client.SendSms(req);// 调用短信发送接口

            if (resp.getSendStatusSet()[0].getCode().equals("Ok")) {
                // 将验证码存储到Redis，并设置过期时间为5分钟
                String key = Constant.RETRIEVE_VERIFICATION_CODE + phoneNumber;//防止冲突
                redisTemplate.opsForValue().set(key, verificationCode, 5, TimeUnit.MINUTES);
                return true;
            } else {
                return false;
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 验证用户输入的验证码
     *
     * @param phoneNumber 手机号码
     * @param userInputCode 用户输入的验证码
     * @return 验证结果
     */
    public boolean retrieveVerifyVerificationCode(String phoneNumber, String userInputCode) {
        String key = Constant.RETRIEVE_VERIFICATION_CODE + phoneNumber;//防止冲突
        String storedCode = redisTemplate.opsForValue().get(key);
        System.out.println(storedCode);
        if (userInputCode.equals(storedCode)) {
            // 验证通过
            return true;
        } else {
            // 验证失败
            return false;
        }
    }


}
